package team.se.tms.dto;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 参数封装Map
 *
 * @author winkyle
 * @date 2018/11/8
 */
public class ParameterMap extends HashMap implements Map {
    private static final long serialVersionUID = 1L;

    private HttpServletRequest request;

    /**
     * 无参构造器
     *
     * @create on 2018/11/8 by winkyle
     */
    public ParameterMap() {
        super();
    }

    /**
     * 将客户端请求信息封装成一个可修改的Map
     * 1.客户端请求信息的map取出request.getParameterMap();
     * 类型应该是Map<String, String[]>，因为请求参数中有多个相同名称的表单
     * 2.因安全机制，此map不可修改，故将map中的值取出，初始化到另一个可修改的map
     * 3.取出的数据如果是数组，用','拼接
     *
     * @param request 客户端请求信息
     * @create on 2018/11/7 by winkyle
     */
    public ParameterMap(HttpServletRequest request) {
        this.request = request;
        Map properties = request.getParameterMap();
        Iterator entries = properties.entrySet().iterator();
        Map.Entry entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if (null == valueObj) {
                value = "";
            } else if (valueObj instanceof String[]) {
                String[] values = (String[]) valueObj;
                for (int i = 0; i < values.length; i++) {
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length() - 1);
            } else {
                value = valueObj.toString();
            }
            put(name, value);
        }
    }

    /**
     * 根据key获取value，如果value是数组，只取第一个
     *
     * @param key key
     * @return 获取到的数据
     * @create on 2018/11/8 by winkyle
     */
    @Override
    public Object get(Object key) {
        Object obj = null;
        if (super.get(key) instanceof Object[]) {
            Object[] arr = (Object[]) super.get(key);
            obj = request == null ? arr : (request.getParameter((String) key) == null ? arr : arr[0]);
        } else {
            obj = super.get(key);
        }
        return obj;
    }

    /**
     * 根据key获取字符串
     *
     * @param key key
     * @return 获取到的字符串
     * @create on 2018/11/8 by winkyle
     */
    public String getString(Object key) {
        return (String) get(key);
    }
}
